//
//  WuliaoViewController.m
//  BMProject
//
//  Created by chris on 16/1/2.
//  Copyright © 2016年 BMProject. All rights reserved.
//

#import "WuliaoViewController.h"
#import "OrderDetailView.h"
#import "MaterialView.h"
#import "DataModel.h"
#import "Detail_haokaCell.h"
#import "BMNetworkHandler.h"
#import "SelectDeliveryMethyVc.h"
#import "DitchManageChangeVc.h"

// 配送类步骤2-确认
@interface WuliaoViewController ()<UITableViewDataSource,UITableViewDelegate>{
    OrderDealDetailOrderInfo *_orderInfo;
    NSMutableArray *_contentList;//OrderDealDetailOrderContentInfo 类型数据
    OrderDealDetailOrderContentInfo *_contentInfo;
    UITableView * _tableview;
    OrderDetailView * _orderDetailView;
}
@end

@implementation WuliaoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"工单信息确认";
    UITableView * tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    tableview.delegate = self;
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableview.sectionHeaderHeight = 8.0;
    tableview.sectionFooterHeight = 8.0;
    tableview.dataSource = self;
    tableview.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 10)];
    _tableview = tableview;
    [self addSubview:tableview];

    [self requestDetail];
    _contentList = [NSMutableArray array];
}
#pragma mark-UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    else
    {
        return _contentList.count;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        static NSString * cellId = @"detailOne";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            OrderDetailView * detail = [[OrderDetailView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 100*ratio_heigth) type:(_model.sign.intValue == 0 ? @"新建" : @"")];
            if (_model.sign.intValue == 0) {
                detail.channelLa.hidden = YES;
            } else {
                detail.channelLa.hidden = NO;
            }
            _orderDetailView = detail;
            [cell.contentView addSubview:detail];
        }
        _orderDetailView.vc = self;
        [_orderDetailView setInfo:_model];
        [_orderDetailView setOrderContentInfo:_contentInfo];
        return cell;
    }
    else
    {
        static NSString * cellId = @"detaiTwo";
        Detail_haokaCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell)
        {
            cell = [[Detail_haokaCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (_model.sign.intValue == 0 && self.type == ORDER_EDIT_TYPE) {//新建
            cell.isCanEdit = YES;
        } else {//确认
            cell.isCanEdit = NO;
        }
        if (_contentList.count > indexPath.row) {
            OrderDealDetailOrderContentInfo *info = _contentList[indexPath.row];
            [cell setInfo:info];
        } else {
            [cell setInfo:nil];
        }
        return cell;
    }
}
#pragma mark-UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 58*ratio_heigth;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        MaterialView * header = [[MaterialView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 58*ratio_heigth)];
        if (_model.type.intValue == 4) {
            header.titleLa.text = @"办公耗材：";
        } else {
            header.titleLa.text = @"物料信息：";
        }
        return header;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 60;
    }
    else
        return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (_type == ORDER_LOOK_TYPE) {
        return nil;
    }
    if (section == 1)
    {
        UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 1, DEF_SCREEN_WIDTH, 60)];
        footer.backgroundColor = [UIColor whiteColor];

        UIImageView * line = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, DEF_SCREEN_WIDTH-20, 1)];
        line.backgroundColor = [UIColor lightGrayColor];
        [footer addSubview:line];
        
        UIButton * sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(DEF_SCREEN_WIDTH/2-50, 20, 100, 30);
        sureBtn.layer.cornerRadius = 5.0;
        sureBtn.layer.masksToBounds = YES;
        sureBtn.backgroundColor = [UIColor orangeColor];
        sureBtn.titleLabel.font = font(13);
        [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureBtn addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:sureBtn];

        if(_model.sign.intValue == 0){
            [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
        }else if(_model.sign.intValue == 1){
            [sureBtn setTitle:@"发货" forState:UIControlStateNormal];
        }

        return footer;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return 120*ratio_heigth;
    }
    return 30*ratio_heigth;
}

- (void) requestDetail {
    //Type=3,4 类型为号卡工单时的返回报文
    [UserServices orderAuditDetailByToen:[[AppDelegate appDelegate] getUserInfo].token
                                      id:_model.id
                                    sign:_model.sign
                                    type:_model.type
                              showDialog:YES
                         completionBlock:^(int result, id responseObject) {
                             if (result == API_Request_Success) {
                                 NSDictionary *responseDict = responseObject[0];
                                 NSDictionary *orderInfoDict              = [responseDict objectForKey:@"orderInfo"];
                                 NSMutableArray *orderContentInfoDic      = [responseDict objectForKey:@"contentList"];
                                 NSMutableArray *poolList                 = [responseDict objectForKey:@"poolList"];//数组

                                 _orderInfo = [[OrderDealDetailOrderInfo alloc] initWithDictionary:orderInfoDict error:nil];
                                 [_contentList removeAllObjects];
                                 [orderContentInfoDic enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                                     OrderDealDetailOrderContentInfo *model = [[OrderDealDetailOrderContentInfo alloc] initWithDictionary:obj error:nil];
                                     if (model) {
                                         [_contentList addObject:model];
                                     }
                                 }];
                                 [_tableview reloadData];
                             }
                         }];
}


/**
 *
 */
- (void) sureBtnAction:(UIButton *) sureBtn{
    DLog(@"确认按钮...");

    if (_model.sign.intValue == 0) {//确认
        if (_contentList == nil || _contentList.count <= 0) {
            [SVProgressHUD showSuccessWithStatus:@"没有可用的号段"];
            return;
        }
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:[[AppDelegate appDelegate] getUserInfo].token forKey:@"token"];
        [params setValue:_model.id forKey:@"basicId"];
        NSString *basicIdStr = @"";
        for (int i = 0; i < _contentList.count; ++i) {
            OrderDealDetailOrderContentInfo *info = _contentList[i];
            basicIdStr = [[basicIdStr stringByAppendingString:info.id] stringByAppendingString:@","];
            NSString *sjAmount =  info.sjAmount;
            if (IsStringEmpty(sjAmount)) {
                [SVProgressHUD showErrorWithStatus:@"实发数据不能为空"];
                return;
            }
            [params setValue:sjAmount forKey:[NSString stringWithFormat:@"sjAmount%i", info.id.intValue]];
        }
        [params setValue:[basicIdStr substringToIndex:basicIdStr.length-1] forKey:@"contentId"];

        [[BMNetworkHandler sharedInstance] conURL:[NSString stringWithFormat:@"%@/order/confirmOpt", API_HOST]
                                      networkType:NetWorkPOST
                                           params:params
                                         delegate:nil
                                          showHUD:YES
                                     successBlock:^(NSData *returnData) {
                                         NSError *error;
//                                      returnData = [NSJSONSerialization JSONObjectWithData:(NSData *) returnData options:nil error:&error];
                                         if (returnData && [returnData isKindOfClass:[NSArray class]]) {
                                             NSDictionary *dictionary = ((NSArray *) returnData)[0];
                                             if ([dictionary objectForKey:@"msg"]) {
                                                 NSString *msg = [dictionary objectForKey:@"msg"];
                                                 NSString *flag = [dictionary objectForKey:@"flag"];
                                                 [SVProgressHUD showInfoWithStatus:msg];
                                                 if (flag.intValue == 0) {
                                                     [self.navigationController popViewControllerAnimated:YES];
                                                     return;
                                                 }
                                                 if ([msg containsString:@"非法"]) {
                                                     [[AppDelegate appDelegate] toLogin];
                                                 }
                                                 //失败
                                                 return;
                                             } else {
                                                 // 成功
                                             }
                                         } else {
                                             //失败
                                         }
                                     } failureBlock:^(NSError *error) {
                }];
    } else if (_model.sign.intValue == 1) {//发货
        [UserServices orderAuditOptByToken:[[AppDelegate appDelegate] getUserInfo].token
                                   basicId:_model.id
                                       opt:@"fahuo"
                               expressName:@""
                                expressNum:@""
                             expressRemark:@""
                                  sendType:@""
                                showDialog:YES
                           completionBlock:^(int result, id responseObject) {
                               SelectDeliveryMethyVc *selectDeliveryMethyVc = [[SelectDeliveryMethyVc alloc] init];
                               selectDeliveryMethyVc.model = _model;
                               [self.navigationController pushViewController:selectDeliveryMethyVc animated:YES];
                           }];

    }


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
